////////////////////////////////////////////////////////////////////////////////
// CppSQLite3 - A C++ wrapper around the SQLite3 embedded database library.
//
// Copyright (c) 2004 Rob Groves. All Rights Reserved. rob.groves@btinternet.com
// 
// Permission to use, copy, modify, and distribute this software and its
// documentation for any purpose, without fee, and without a written
// agreement, is hereby granted, provided that the above copyright notice, 
// this paragraph and the following two paragraphs appear in all copies, 
// modifications, and distributions.
//
// IN NO EVENT SHALL THE AUTHOR BE LIABLE TO ANY PARTY FOR DIRECT,
// INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST
// PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION,
// EVEN IF THE AUTHOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// THE AUTHOR SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
// PARTICULAR PURPOSE. THE SOFTWARE AND ACCOMPANYING DOCUMENTATION, IF
// ANY, PROVIDED HEREUNDER IS PROVIDED "AS IS". THE AUTHOR HAS NO OBLIGATION
// TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
//
// V3.0		03/08/2004	-Initial Version for sqlite3
//
// V3.1		16/09/2004	-Implemented getXXXXField using sqlite3 functions
//						-Added CppSQLiteDB3::is_table_exist()
////////////////////////////////////////////////////////////////////////////////
#ifndef _CppSQLite3_H__
#define _CppSQLite3_H__

#include <sys/sys_asy.h>
#include <interface/data_interface.h>
#include <cstdio>
#include <cstring>
#include "sqlite3.h"



#define CPPSQLITE_ERROR 1000

class CppSQLite3Exception
{
public:

    CppSQLite3Exception(const int nErrCode,
                    char* szErrMess,
                    bool bDeleteMsg=true);

    CppSQLite3Exception(const CppSQLite3Exception&  e);

    virtual ~CppSQLite3Exception();

    const int errorCode() { return mnErrCode; }

    const char* errorMessage() { return mpszErrMess; }

    static const char* errorCodeAsString(int nErrCode);
    static void print_err_msg(const int err_code, char* err_msg, bool bDeleteMsg = false);

private:

    int mnErrCode;
    char* mpszErrMess;
};


class CppSQLite3Buffer
{
public:

    CppSQLite3Buffer();

    ~CppSQLite3Buffer();

    const char* format(const char* szFormat, ...);

    operator const char*() { return mpBuf; }

    void clear();

private:

    char* mpBuf;
};


class CppSQLite3Binary
{
public:

    CppSQLite3Binary();

    ~CppSQLite3Binary();

    void setBinary(const unsigned char* pBuf, int nLen);
    void setEncoded(const unsigned char* pBuf);

    const unsigned char* getEncoded();
    const unsigned char* getBinary();

    int getBinaryLength();

    unsigned char* allocBuffer(int nLen);

    void clear();

private:

    unsigned char* mpBuf;
    int mnBinaryLen;
    int mnBufferLen;
    int mnEncodedLen;
    bool mbEncoded;
};

class CppSQLite3Query
{
public:

    CppSQLite3Query();

    CppSQLite3Query(const CppSQLite3Query& rQuery);

    CppSQLite3Query(sqlite3* pDB,
				sqlite3_stmt* pVM,
                bool bEof,
                bool bOwnVM=true);

    CppSQLite3Query& operator=(const CppSQLite3Query& rQuery);

    virtual ~CppSQLite3Query();

    int get_fields_count();

    int fieldIndex(const char* szField);
    const char* get_field_name(int nCol);

    const char* fieldDeclType(int nCol);
    int fieldDataType(int nCol);

    int get_field_value_int(int nField, int nNullValue=0);
    int get_field_value_int(const char* szField, int nNullValue=0);

    double get_field_value_float(int nField, double fNullValue=0.0);
    double get_field_value_float(const char* szField, double fNullValue=0.0);

    const char* get_string_field(int nField, const char* szNullValue="");
    const char* get_string_field(const char* szField, const char* szNullValue="");

    const unsigned char* getBlobField(int nField, int& nLen);
    const unsigned char* getBlobField(const char* szField, int& nLen);

    bool field_is_null(int nField);
    bool field_is_null(const char* szField);

    bool eof();

    void nextRow();

    void finalize();
public:
	const char* get_field_value_i(int nField);
	const char* get_field_value_i(const char* szField);
private:

    bool checkVM();

	sqlite3* mpDB;
    sqlite3_stmt* mpVM;
    bool mbEof;
    int mnCols;
    bool mbOwnVM;
};


class sqlite3_table_impl : public aot::data::isqlite3_table
{
public:
    sqlite3_table_impl();
    sqlite3_table_impl(const sqlite3_table_impl& table);
    sqlite3_table_impl(char** results, int rows, int cols);
    virtual ~sqlite3_table_impl();
    sqlite3_table_impl& operator=(const sqlite3_table_impl& table);
public:
    virtual int get_fields_count();
    virtual int get_rows_count();
    virtual const char* get_field_name(int index);
	virtual const char* get_field_value(int index, const char* def);
	virtual const char* get_field_value(const char* name, const char* def); 

    virtual bool field_is_null(int index);
    virtual bool field_is_null(const char* name);

    virtual void set_row_index(int row);
    virtual void finalize();
private:
	const char* get_field_value_i(int index);
	const char* get_field_value_i(const char* name); 
    void check_results();

    int cols_;
    int rows_;
    int current_row_;
    char** results_;
};


class CppSQLite3Statement
{
public:
    CppSQLite3Statement();
    CppSQLite3Statement(const CppSQLite3Statement& rStatement);
    CppSQLite3Statement(sqlite3* pDB, sqlite3_stmt* pVM);
    virtual ~CppSQLite3Statement();
    CppSQLite3Statement& operator=(const CppSQLite3Statement& rStatement);
    int exec();
    CppSQLite3Query execQuery();

    void bind(int nParam, const char* szValue);
    void bind(int nParam, const int nValue);
    void bind(int nParam, const double dwValue);
    void bind(int nParam, const unsigned char* blobValue, int nLen);
    void bindNull(int nParam);

    void reset();
    void finalize();
private:
    bool checkDB();
    bool checkVM();

    sqlite3* mpDB;
    sqlite3_stmt* mpVM;
};


class CppSQLite3DB
{
public:
    CppSQLite3DB();
    virtual ~CppSQLite3DB();
    
    void open(const char* szFile);
    void close();
	bool is_table_exist(const char* szTable);
    int exec(const char* szSQL);
    CppSQLite3Query execQuery(const char* szSQL);
    int exec_scalar(const char* szSQL);
    sqlite3_table_impl exec_and_get_record(const char* szSQL);
    bool exec_and_get_record(const char* szSQL,aot::data::isqlite3_table** pTable);
    CppSQLite3Statement compileStatement(const char* szSQL);
    sqlite_int64 lastRowId();
    void interrupt() { sqlite3_interrupt(mpDB); }
    void setBusyTimeout(int nMillisecs);
    static const char* SQLiteVersion() { return SQLITE_VERSION; }
private:
    CppSQLite3DB(const CppSQLite3DB& db);
    CppSQLite3DB& operator=(const CppSQLite3DB& db);
    sqlite3_stmt* compile(const char* szSQL);
    bool checkDB();
    sqlite3* mpDB;
    int mnBusyTimeoutMs;
};

class sqlite3_db_impl : public aot::data::isqlite3_db
{
public:
    sqlite3_db_impl();
    virtual ~sqlite3_db_impl();
    virtual void destroy(){};
    
    virtual bool init(const char* user_id, bool sys_cfg);
    virtual bool is_inited();
    virtual bool is_sys_cfg();
    virtual bool is_table_exist(const char* table_name);
    virtual int exec(const char* sql_str);
    virtual int exec_scalar(const char* sql_str);
    virtual bool exec_and_get_record(const char* sql_str, aot::data::isqlite3_table** out);
public:
    virtual bool init_by_db_full_path(const char* db_path);
protected:
    bool create_db(const char* db_temp_filename, const char* new_db_path);

protected:
    bool is_inited_;
    bool is_syscfg_;
    CppSQLite3DB* db_;
    xy::thread_mutex			lock_;

    typedef xy::auto_lock<xy::thread_mutex>		auto_lock_type;
};


#endif
